﻿#$language = "Python"
#$interface = "1.0"

import os
import sys
import subprocess
import _subprocess
import ConfigParser

g_local_path = os.path.dirname(os.path.abspath(__file__))
if g_local_path not in sys.path:
    sys.path.insert(0, g_local_path)

import crnc
import debug
from const import *
from counter_const import *

def hide_window():
    hide_info = subprocess.STARTUPINFO()
    hide_info.dwFlags = _subprocess.CREATE_NEW_CONSOLE | \
                        _subprocess.STARTF_USESHOWWINDOW
    hide_info.wShowWindow = _subprocess.SW_HIDE
    return hide_info

def external_frame(counters):
    feature_list = []
    counter_list = []
    for key in counters:
        if key == COUNTER_INDIVIDUAL:
            counter_list = counters[key]
        else:
            feature_list.append(key)

    input_msg = []
    input_msg.extend(feature_list)
    input_msg.append(COUNTER_MSG_FEATURE)
    input_msg.extend(counter_list)
    input_msg.append(COUNTER_MSG_INDIVIDUAL)
    
    del feature_list
    del counter_list
    
    args = CONST_PYTHON + ' ' + g_local_path + '\\' + COUNTER_FRAME
    proc = subprocess.Popen(args, 
                            shell=False, 
                            stdin=subprocess.PIPE, 
                            stdout=subprocess.PIPE, 
                            startupinfo=hide_window())

    std_out, std_err = proc.communicate((os.linesep).join(input_msg))
    lines = filter(lambda x: x != '', std_out.splitlines())  # del blan lines

    del input_msg

    line_num = 0
    receive_list = []
    while line_num < len(lines):
        if lines[line_num] == COUNTER_MSG_ACT:
            line_num += 1
            action = int(lines[line_num])
            if action == 0:
                break
        elif lines[line_num] == COUNTER_MSG_TYPE:
            line_num += 1
            counter_choice = int(lines[line_num])
        elif lines[line_num] == COUNTER_MSG_LIST:
            del receive_list[:]
        else:
            receive_list.append(lines[line_num])
        line_num += 1

    rslt_counter_list = []
    if action != 0:
        if counter_choice == 1:
            for var in receive_list:
                rslt_counter_list.extend(counters[var])
        elif counter_choice == 2:
            rslt_counter_list = receive_list
        else:
            action = 0
    return action, rslt_counter_list

class TraceCounter():
    trace_enabled = False
    def __init__(self, obj, counter_list, active=False):
        self.crt = obj
        if len(counter_list) > 0:
            self.trace_enabled = True
            if active:
                self._active_hex = '2'
                self._active_str = 'Activate'
            else:
                self._active_hex = '4'
                self._active_str = 'Deactivate'

            self.log = debug.Log('counter: ')
            self.rnc = crnc.cRNC(self.crt, False)
            self._open_config()
            self.rnc.enter_icsu()
            for counter in counter_list:
                self._counter = counter
                self._trace_counter()
            self.rnc.goto_top()

    def __del__(self):
        if self.trace_enabled:
            del self.log
            del self.rnc
            del self.cfg

    def _open_config(self):
        self.cfg = ConfigParser.SafeConfigParser()
        self.cfg.read(g_local_path + '\\counter.ini')

    def _trace_counter(self):
        self._module_type_hex = '{0:X}'.format(int(self._counter[1:5]))
        self._counter_hex = '{0:X}'.format(int(self._counter[6:]))
    
        rslt = False
        try:
            counter_modules = self.cfg.get(self._counter, 'Module')
        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
            msg = 'Unknown counter "' + self._counter + \
                  '" in configuration File.'
            self.log.w(msg, head='Warning: ')
        else:
            for module in counter_modules.split(','):
                if self._get_module_hex(module.strip()[:3]):
                    rslt = self._send_command()
        return rslt

    def _get_module_hex(self, module):
        for key in COUNTER_MODULE_DICT.keys():
            if module == key:
                self._module_hex = COUNTER_MODULE_DICT[key]
                rslt = True
                break
        else:
            msg = 'Unknown counter module ' + \
                  '"{0}" for {1}.'.format(module, self._counter)
            self.log.w(msg, head='Warning: ')
            self._module_hex = ''
            rslt = False
        return rslt

    def _send_command(self):
        mml = 'ZOS:*,*,' + self._module_hex \
                + ',0,,,,CDAA,,,XDFFFFFFFF,XDFFFFFFFF,XDFFFFFFFF' \
                + ',XD' + self._active_hex \
                + ',XD' + self._module_type_hex \
                + ',XD' + self._counter_hex
        msg = '{0} {1}: {2}'.format(self._active_str, self._counter, mml)
        self.log.w(msg)
        self.crt.Screen.Send(mml + '\r')
        self.crt.Screen.WaitForString('-OSC>', 2)
        return True

def trace_counters(obj, counters):
    active, counter_list = external_frame(counters)
    if active != 0:
        t = TraceCounter(obj, counter_list, (True if active > 0 else False))
        del t
    return 0

if __name__ == '__main__':
    counters = {
        'CR1024':  ['M1002C679', 'M1002C689', 'M1002C690', 'M1002C691', \
                    'M1006C209', 'M1006C210', 'M1006C245', 'M1006C247', \
                    'M1006C302'],
        'RAN2963': ['M1006C309'],
        'RAN1910': ['M1006C309'],
        'RAN1913': ['M1006C309'],
        COUNTER_INDIVIDUAL:['M1000C999', 'M1001C999', 'M1002C999', 'M1006C999']
    }
    action, counter_list = external_frame(counters)
    if action == 0:
        print('No Operate[%d]'%(action))
    if action != 0:
        if action > 0:
            print('Activate[%d]'%(action))
        elif action < 0:
            print('Deactivate[%d]'%(action))
        for var in counter_list:
            print var
